package zkdemo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.client.ZooKeeperSaslClient;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.security.acl.Acl;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName ZKApiTest
 * @Description TODO
 * @Author Kristin
 * @Date 2021/06/22 16:04:12
 * @Version 1.0.0
 */
public class ZKApiTest {


    public void eventMonitor() throws Exception {
        ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 20000, new Watcher() {
            public void process(WatchedEvent event) {
                System.out.println("链接建立");
            }
        });

        System.out.println(zk.exists("/node2", null));
        // 创建一个节点
//        String nodeId = zk.create("/lock" , new byte[0],ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        // 注册一个监听事件
//        zk.getData(nodeId, new NodeWatch(),null);
//        // 删除一个节点
//
//        zk.setData(nodeId, "kristin".getBytes(), -1);
//
//        zk.getData(nodeId, new NodeWatch(),null);
//
//        zk.delete(nodeId, -1);
    }

    public static void main(String[] args) throws Exception {
        new ZKApiTest().eventMonitor();
        // 创建zk链接
//        ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 20000, null);

//        zk.create("/server" , "server".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);


//        zk.create("/server/server1" , "192.168.1.1".getBytes(),  ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//        zk.create("/server/server2" , "192.168.1.2".getBytes(),  ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//        zk.create("/server/server3" , "192.168.1.3".getBytes(),  ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//        System.out.println("12345");


        // 创建父节点
//        String path = zk.create("/kristin2", "this is kristin2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//        System.out.println(path);

        // 创建子节点
//        System.out.println(zk.create("/kristin2/k1", "this is k1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));


        // 获取节点中的信息（获取父节点+子节点的值）
//        byte[] data = zk.getData("/kristin2/k1", true, null);
//        String value = new String(data);
//        System.out.println(value);

//        List<String> values = zk.getChildren("/kristin2", true , null);
//        for(String str : values) {
//            System.out.println(str);
//        }


        // 修改节点的值
//        Stat stat = zk.setData("/kristin/k1", "kkkkkkkkkkkkk1".getBytes(), -1);
//        System.out.println(stat);
        // 移除节点的值

//        System.out.println(zk.exists("/kristin2/k1", true));

    }

}
